package com.woniuxy.flowable.controller;

import com.woniuxy.flowable.service.BaoxiuProcessService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/baoxiu")
public class BaoxiuController {

    @Autowired
    private BaoxiuProcessService baoxiuProcessService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private TaskService taskService;

    /**
     * 部署流程
     */
    @PostMapping("/deploy")
    public ResponseEntity<Map<String, Object>> deployProcess() {
        try {
            Deployment deployment = baoxiuProcessService.deployProcess();
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("deploymentId", deployment.getId());
            result.put("message", "流程部署成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("流程部署失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "流程部署失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 启动流程
     */
    @PostMapping("/start")
    public ResponseEntity<Map<String, Object>> startProcess(@RequestBody Map<String, Object> request) {
        try {
            Long repairOrderId = Long.valueOf(request.get("repairOrderId").toString());
            Long yezhu = Long.valueOf(request.get("yezhu").toString());
            Long wuye = Long.valueOf(request.get("wuye").toString());
            Long weixiu = Long.valueOf(request.get("weixiu").toString());
            String description = request.get("description").toString();
            
            ProcessInstance processInstance = baoxiuProcessService.startProcess(repairOrderId, yezhu, wuye, weixiu, description);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("processInstanceId", processInstance.getId());
            result.put("message", "流程启动成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("流程启动失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "流程启动失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询用户任务
     */
    @GetMapping("/tasks/{assignee}")
    public ResponseEntity<Map<String, Object>> getUserTasks(@PathVariable String assignee) {
        try {
            List<Task> tasks = baoxiuProcessService.getUserTasks(assignee);

            // 只返回需要的字段，避免懒加载异常
            List<Map<String, Object>> simpleTasks = tasks.stream().map(task -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", task.getId());
                map.put("name", task.getName());
                map.put("assignee", task.getAssignee());
                map.put("createTime", task.getCreateTime());
                return map;
            }).collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("tasks", simpleTasks);
            result.put("count", simpleTasks.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询任务失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "查询任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询所有任务
     */
    @GetMapping("/tasks")
    public ResponseEntity<Map<String, Object>> getAllTasks() {
        try {
            List<Task> tasks = baoxiuProcessService.getAllTasks();

            // 只返回需要的字段，避免懒加载异常
            List<Map<String, Object>> simpleTasks = tasks.stream().map(task -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", task.getId());
                map.put("name", task.getName());
                map.put("assignee", task.getAssignee());
                map.put("createTime", task.getCreateTime());
                return map;
            }).collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("tasks", simpleTasks);
            result.put("count", simpleTasks.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询所有任务失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "查询所有任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 完成任务
     */
    @PostMapping("/complete")
    public ResponseEntity<Map<String, Object>> completeTask(@RequestBody Map<String, String> request) {
        try {
            String taskId = request.get("taskId");
            String outcome = request.get("outcome");
            
            if (outcome != null && !outcome.isEmpty()) {
                baoxiuProcessService.completeTask(taskId, outcome);
            } else {
                baoxiuProcessService.completeTask(taskId);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "任务完成成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("完成任务失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "完成任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取流程实例信息
     */
    @GetMapping("/process/{processInstanceId}")
    public ResponseEntity<Map<String, Object>> getProcessInstanceInfo(@PathVariable String processInstanceId) {
        try {
            ProcessInstance processInstance = baoxiuProcessService.getProcessInstance(processInstanceId);
            
            // 获取当前任务
            List<Task> currentTasks = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .list();
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("processInstanceId", processInstanceId);
            result.put("businessKey", processInstance.getBusinessKey());
            result.put("processDefinitionId", processInstance.getProcessDefinitionId());
            result.put("currentTasks", currentTasks.stream().map(task -> {
                Map<String, Object> taskInfo = new HashMap<>();
                taskInfo.put("id", task.getId());
                taskInfo.put("name", task.getName());
                taskInfo.put("assignee", task.getAssignee());
                taskInfo.put("createTime", task.getCreateTime());
                return taskInfo;
            }).collect(Collectors.toList()));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取流程实例信息失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取流程实例信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    @Autowired
    HistoryService historyService;
    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;

    /**
     * 查看流程图并高亮当前节点
     */
    @GetMapping("/process/diagram/{processInstanceId}")
    public void getProcessDiagram(@PathVariable String processInstanceId, HttpServletResponse response) throws IOException {

        List<HistoricActivityInstance> historyActivityList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceId().asc()
                .list();
        if (historyActivityList == null || historyActivityList.isEmpty()) {
            throw new RuntimeException("该流程实例没有历史节点，无法生成流程图。请确认流程已启动并至少流转过一个节点。");
        }
        List<String> executedActivityIdList = historyActivityList.stream()
                .map(HistoricActivityInstance::getActivityId)
                .collect(Collectors.toList());
        String processDefinitionId = historyActivityList.get(0).getProcessDefinitionId();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);

        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(
                bpmnModel,
                "png",
                executedActivityIdList,
                Collections.emptyList(),
                processEngineConfiguration.getActivityFontName(),
                processEngineConfiguration.getLabelFontName(),
                processEngineConfiguration.getAnnotationFontName(),
                processEngineConfiguration.getClassLoader(),
                1.0,
                true
        );

        response.setContentType("image/png");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, len);
        }
        in.close();

    }

    /**
     * 物业审批
     */
    @PostMapping("/{repairOrderId}/approve")
    public ResponseEntity<Map<String, Object>> approveRepairFlow(
            @PathVariable Long repairOrderId,
            @RequestBody Map<String, Object> request) {
        try {
            Boolean approved = Boolean.valueOf(request.get("approved").toString());
            String comment = request.get("comment") != null ? request.get("comment").toString() : null;
            String userId = request.get("userId").toString();
            
            baoxiuProcessService.approveRepair(repairOrderId, approved, comment, userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", approved ? "审批通过成功" : "审批驳回成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("物业审批失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "审批失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 维修人员处理报修单
     */
    @PostMapping("/{repairOrderId}/handle")
    public ResponseEntity<Map<String, Object>> handleRepairFlow(
            @PathVariable Long repairOrderId,
            @RequestBody Map<String, Object> request) {
        try {
            Boolean completed = Boolean.valueOf(request.get("completed").toString());
            String feedback = request.get("feedback") != null ? request.get("feedback").toString() : null;
            String repairResult = request.get("repairResult") != null ? request.get("repairResult").toString() : null;
            String userId = request.get("userId").toString();
            
            baoxiuProcessService.handleRepair(repairOrderId, completed, feedback, repairResult, userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", completed ? "维修完成" : "维修处理中");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("维修处理失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "维修处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 查询维修人员的待处理任务
     */
    @GetMapping("/repair/tasks/{userId}")
    public ResponseEntity<Map<String, Object>> getRepairTasks(@PathVariable String userId) {
        try {
            List<Task> tasks = baoxiuProcessService.getRepairTasks(userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("tasks", tasks);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询维修任务失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "查询维修任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

} 